package com.wzb.mybatisplus.bitaction.electrumaction;

import javax.net.ssl.*;
import java.io.*;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;

public class SSLContextFactory {

    public static SSLSocketFactory createCustomSSLSocketFactory() {
        try {
            // 创建空的 KeyStore
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null, null);

            // 这里你需要获取服务器的证书文件(.crt或.pem)
            // 你可以用浏览器访问 https://your-electrum-server:50002 导出证书
            // 或者使用 openssl 命令：openssl s_client -connect electrum.bitaroo.net:50002 </dev/null 2>/dev/null | openssl x509 > server.crt

            // 加载证书
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            InputStream certStream = new FileInputStream("server.crt"); // 你的证书文件
            Certificate cert = cf.generateCertificate(certStream);

            // 将证书添加到 KeyStore
            keyStore.setCertificateEntry("electrum-server", cert);

            // 创建 TrustManager 使用我们的 KeyStore
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(keyStore);

            // 创建 SSLContext
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, tmf.getTrustManagers(), null);

            return sslContext.getSocketFactory();

        } catch (Exception e) {
            throw new RuntimeException("创建自定义 SSL SocketFactory 失败", e);
        }
    }
}